package 线程创建.Callable接口;


import org.apache.commons.io.FileUtils;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//Callable<Boolean>中<Boolean>是设置返回值类型，他要与call()方法的返回值一致
public class testThread1 implements Callable<Boolean> {
    String url;
    String name;
    public testThread1 (String url,String name){
        this.name=name;
        this.url=url;
    }
    @Override
    public Boolean call() {
        wedDownloader wedDownloader = new wedDownloader();
        wedDownloader.downloader(url,name);
        System.out.println("下载的文件明为："+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        testThread1 t1 = new testThread1("http://images.china.cn/site1000/2020-08/03/5971d9dc-3cd4-4cec-ad8d-5a6dcfdfc6fd.jpg","冰川1.jpg");
        testThread1 t2 = new testThread1("http://images.china.cn/site1000/2020-08/03/3e0b7ff7-6860-4fec-8387-9ecdc17887fc.jpg","冰川2.jpg");
        testThread1 t3 = new testThread1("http://images.china.cn/site1000/2020-08/03/5faadc7d-4671-46de-a75d-eaadc4d30359.jpg","冰川3.jpg");

        FutureTask futureTask = new FutureTask(t1);

        //创建开启执行服务，这里的3是设置线程池中开启线程的个数
        ExecutorService ser= Executors.newFixedThreadPool(3);
        //提交执行的线程代码，开启线程
        Future<Boolean> re1= ser.submit(t1);
        Future<Boolean> re2= ser.submit(t2);
        Future<Boolean> re3= ser.submit(t3);
        //获取线程执行的返回值
        boolean a1=re1.get();
        boolean a2=re2.get();
        boolean a3=re3.get();
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);
        //关闭线程
        ser.shutdownNow();



    }
}

//下载器
class wedDownloader{
    //下载方法
    public void downloader(String url,String name){
        try {
            //下载commons-io工具提供的下载方法
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
